

#include "XmlParser.h"
#include "XmlUtil.h"
#include "XmlDefs.h"
#include "xercesc/dom/DOMException.hpp"
#include "xercesc/util/XMLUniDefs.hpp"

struct XmlParser {

  XmlParser() {}
  
  static XmlParser* instanceCreationHook();

  ~XmlParser();
  
  static DOMBuilder* parser;
};

DOMBuilder* XmlParser::parser = NULL;

XmlParser* 
XmlParser::instanceCreationHook() {
  if( parser != NULL)
    return awa::Singleton<XmlParser>::Instance();
  try {
    XMLPlatformUtils::Initialize();
  }
  catch(...){
    throw;
  }
  
  const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
  DOMImplementationLS* Impl;
  Impl = (DOMImplementationLS*)DOMImplementationRegistry::getDOMImplementation(gLS);
  
  parser = Impl->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
  
}

XmlParser::~XmlParser() {

  parser->release();
  parser = NULL;
  
  XMLPlatformUtils::Terminate();

}

DOMBuilder* xerces::getXmlParser() {

  if(XmlParser::parser)
    return XmlParser::parser;
  
  DOMBuilder* parser;
  parser = awa::Singleton<XmlParser>::Instance()->parser;
  // Ignore whitespace by default
  parser->setFeature(XMLUni::fgDOMWhitespaceInElementContent, false);

  return parser;
}

struct XmlWriter {

  XmlWriter() {}
  
  static XmlWriter* instanceCreationHook();

  ~XmlWriter();
  
  static DOMWriter* writer;
};


DOMWriter* XmlWriter::writer = NULL;

XmlWriter* 
XmlWriter::instanceCreationHook() {
  if( writer != NULL)
    return awa::Singleton<XmlWriter>::Instance();
  try {
    XMLPlatformUtils::Initialize();
  }
  catch(...){
    throw;
  }
  
  const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
  DOMImplementationLS* Impl;
  Impl = (DOMImplementationLS*)DOMImplementationRegistry::getDOMImplementation(gLS);
  
  writer = Impl->createDOMWriter();
  
}

XmlWriter::~XmlWriter() {

  writer->release();
  writer = NULL;
  
  // XMLPlatformUtils::Terminate();

}

DOMWriter* xerces::getXmlWriter() {

  if(XmlWriter::writer)
    return XmlWriter::writer;
  
  DOMWriter* writer;
  writer = awa::Singleton<XmlWriter>::Instance()->writer;
  // Ignore whitespace by default
  writer->setFeature(XMLUni::fgDOMWhitespaceInElementContent, false);

  return writer;
}
